package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.RegionInfo;
import cc.rengu.redp.bizimpl.upmp.service.RegionInfoService;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.domain.RedpResponse;
import cc.rengu.redp.common.exception.RedpException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiuYuLiang.LL
 */
@Slf4j
@Validated
@Api(tags = "参数管理:行政区划代码管理")
@RestController
@RequestMapping("/admin/merParam/regionInfo")
public class RegionInfoController extends BaseController {
    @Autowired
    private RegionInfoService regionInfoService;

    @GetMapping
//    @RequiresPermissions("regionInfo:view")
    public Map<String, Object> list(QueryRequest request, RegionInfo entity) {
        return getDataTable(this.regionInfoService.findByPage(request, entity));
    }

    @Log("查询单条")
    @GetMapping(value = "/getOne")
    @ApiImplicitParam(paramType = "query", name = "id", value = "id主键", required = true, dataType = "String")
    public RegionInfo getOne(@NotBlank(message = "{required}") String id) {
        RegionInfo entity = regionInfoService.getById(id);
        if (Common.isNotBlank(entity.getParentCode())) {
            LambdaQueryWrapper<RegionInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RegionInfo::getRegionCode, entity.getParentCode());
            wrapper.eq(RegionInfo::getStatus, BusinessContainer.data_sta_00);
            RegionInfo parent = regionInfoService.getOne(wrapper);
            if (parent != null)
                entity.setParentName(parent.getRegionName());
        }
        return entity;
    }

    @Log("新增")
    @PostMapping
//    @RequiresPermissions("regionInfo:add")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "regionCode", value = "行政区划代码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "regionName", value = "行政区划名称", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "regionLevel", value = "行政级别", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "areaCode", value = "对应银联地区代码", required = true, dataType = "String")
    })
    public void add(@Valid RegionInfo entity) throws RedpException {
        try {
            this.regionInfoService.create(entity);
        } catch (Exception e) {
            String message = "新增失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    @Log("修改")
    @PutMapping("/update")
//    @RequiresPermissions("regionInfo:update")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "id主键", required = true, dataType = "String")
    })
    public void update(@Valid RegionInfo entity) throws RedpException {
        try {
            this.regionInfoService.update(entity);
        } catch (Exception e) {
            String message = "修改失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    @Log("注销")
    @PutMapping("/cancel")
//    @RequiresPermissions("regionInfo:cancel")
    @ApiImplicitParam(paramType = "query", name = "id", value = "id主键", required = true, dataType = "String")
    public void cancel(@NotBlank(message = "{required}") String id) throws RedpException {
        try {
            this.regionInfoService.cancel(id);
        } catch (Exception e) {
            String message = "注销失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    @Log("删除")
    @DeleteMapping("/{ids}")
//    @RequiresPermissions("regionInfo:delete")
    @ApiImplicitParam(paramType = "path", name = "ids", value = "id主键，逗号隔开", required = true, dataType = "String")
    public void delete(@NotBlank(message = "{required}") @PathVariable String ids) throws RedpException {
        try {
            this.regionInfoService.delete(ids.split(StringPool.COMMA));
        } catch (Exception e) {
            String message = "删除类目失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    @PostMapping(value = "/check")

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "id主键", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "regionCode", value = "行政区划代码", dataType = "String")
    })
    public RedpResponse check(String id, String regionCode) throws RedpException {
        LambdaQueryWrapper<RegionInfo> wrapper = new LambdaQueryWrapper();
        if (StringUtils.checkValNotNull(regionCode)) {
            if (StringUtils.checkValNotNull(id)) {
                wrapper.ne(RegionInfo::getId, id);
            }
            wrapper.eq(RegionInfo::getRegionCode, regionCode);
            RegionInfo info = regionInfoService.getOne(wrapper);
            if (null != info) {
                throw new RedpException("[ 行政区划代码 ] 重复，请重新输入");
            }
        }
        return new RedpResponse().message("验证成功");
    }

    /**
     * 行政区划代码下拉数据
     *
     * @param model
     * @param q     条件
     * @param p     上级行政区划代码
     * @param l     行政级别
     * @return
     */
    @ApiOperation("行政区划代码下拉数据")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "q", value = "条件", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "p", value = "上级行政区划代码或名称", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "l", value = "行政级别", dataType = "String")
    })
    @GetMapping(value = "/select2")
    public List<Map<String, Object>> tagsData(Model model, @RequestParam(value = "q", required = false) String q, @RequestParam(value = "p", required = false) String p, @RequestParam(value = "l", required = false) String l) throws UnsupportedEncodingException {
        List<RegionInfo> regionInfos = new ArrayList<>();
        if (StringUtils.isNotBlank(p)) {
            // 处理上级行政区划代码为中文的情况，利用中文名称获取英文编码
            p = URLDecoder.decode(p, "UTF-8");
            LambdaQueryWrapper<RegionInfo> wrapper = new LambdaQueryWrapper();
            String finalP = p;
            wrapper.or(qw -> qw.likeRight(RegionInfo::getRegionCode, finalP).likeRight(RegionInfo::getRegionName, finalP));
            regionInfos = regionInfoService.list(wrapper);
            if (regionInfos.size() > 0) {
                p = regionInfos.get(0).getRegionCode();
            }
        }
        LambdaQueryWrapper<RegionInfo> wrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(q)) {
            wrapper.or(qw -> qw.likeRight(RegionInfo::getRegionName, q).likeRight(RegionInfo::getRegionCode, q))
                    .eq(RegionInfo::getStatus, BusinessContainer.data_sta_01);
        }
        if (StringUtils.isNotBlank(l)) {
            if ((l.equals(BusinessContainer.REGION_LEVEL_CITY) || l.equals(BusinessContainer.REGION_LEVEL_AREA)) && StringUtils.isNotBlank(p)) {
                if (BusinessContainer.REGION_CODE_BEIJING.equals(p)
                        || BusinessContainer.REGION_CODE_TIANJIN.equals(p)
                        || BusinessContainer.REGION_CODE_SHANGHAI.equals(p)
                        || BusinessContainer.REGION_CODE_CHONGQING.equals(p)) {
                    wrapper.eq(RegionInfo::getParentCode, p);
                } else {
                    wrapper.eq(RegionInfo::getRegionLevel, l);
                    wrapper.eq(RegionInfo::getParentCode, p);
                }
            } else {
                wrapper.eq(RegionInfo::getRegionLevel, l);
            }
        }
        regionInfos = regionInfoService.list(wrapper);
        String sameStr = "";
        if ("02".equals(l) || "03".equals(l)) {
            LambdaQueryWrapper<RegionInfo> one = new LambdaQueryWrapper();
            one.eq(RegionInfo::getRegionCode, p);
            sameStr = regionInfoService.getOne(one).getRegionName();
        }
        List<Map<String, Object>> items = Lists.newArrayList();
        for (RegionInfo regionInfo : regionInfos) {
            Map<String, Object> item = Maps.newHashMap();
            item.put("id", regionInfo.getRegionCode());
            item.put("name", regionInfo.getRegionName().replace(sameStr, ""));
            items.add(item);
        }
        return items;
    }

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "q", value = "行政区划代码|行政区划名称|行政级别", dataType = "String"),
    })
    @GetMapping(value = "/regionInfoSelect2List")
    public Map<String, Object> regionInfoSelect2List(String q) {
        LambdaQueryWrapper<RegionInfo> wrapper = new LambdaQueryWrapper();
        if (StringUtils.checkValNotNull(q)) {
            wrapper.and(wp -> wp.likeRight(RegionInfo::getRegionCode, q).
                    or().likeRight(RegionInfo::getRegionName, q).or().likeRight(RegionInfo::getRegionLevel, q));
        }
        wrapper.eq(RegionInfo::getStatus, BusinessContainer.data_sta_01);
        List<RegionInfo> listx = regionInfoService.list(wrapper);
        Map<String, Object> maps = new HashMap<String, Object>();
        Map<String, String> map = new HashMap<String, String>();
        List<Object> list = new ArrayList<Object>();
        if (listx != null) {
            for (int i = 0; i < listx.size(); i++) {
                RegionInfo mer = listx.get(i);
                map = new HashMap<String, String>();
                map.put("id", mer.getRegionCode());
                map.put("name", mer.getRegionName());
                // map.put("level",org.getOrgLevel());
                list.add(map);
            }
            maps.put("results", list);
            maps.put("more", false);
        }
        return maps;
    }


    /**
     * 获取省市区
     * makeby   --lizk
     *
     * @param q regionCode
     * @param p parentCode
     * @param l 级别
     * @return
     */
    @GetMapping("select3")
    public RegionInfo findPrncCityArea(@RequestParam(value = "q", required = false) String q,
                                       @RequestParam(value = "p", required = false) String p,
                                       @RequestParam(value = "l", required = false) String l) {

        return regionInfoService.findPrncCityArea(q, p, l);
    }


    /**
     * 新增行政区划代码中获取上级行政区划代码
     * makeby   --lizk
     *
     * @param l 级别
     * @return
     */
    @GetMapping("select4")
    public List<Map<String, Object>> findRegionCode(@RequestParam(value = "l", required = false) String l) {
        LambdaQueryWrapper<RegionInfo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(RegionInfo::getRegionLevel, l);
        List<RegionInfo> list = regionInfoService.list(wrapper);
        List<Map<String, Object>> items = Lists.newArrayList();
        for (RegionInfo regionInfo : list) {
            Map<String, Object> item = Maps.newHashMap();
            item.put("id", regionInfo.getRegionCode());
            item.put("name", regionInfo.getRegionName());
            items.add(item);
        }
        return items;
    }

    /**
     * 获取上级行政区划名称
     * makeby   --lizk
     *
     * @param q regionCode
     * @param l 级别
     * @return
     */
    @GetMapping("select5")
    public RegionInfo findParentCode(@RequestParam(value = "q", required = false) String q,
                                       @RequestParam(value = "l", required = false) String l) {
        LambdaQueryWrapper<RegionInfo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(RegionInfo::getRegionLevel, l);
        if (StringUtils.isNotBlank(q)){
            wrapper.eq(RegionInfo::getRegionCode, q);
        }
        return regionInfoService.getOne(wrapper);
    }
}
